package com.sphd.emanu.activity.orgsetting;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.github.yoojia.inputs.AndroidNextInputs;
import com.github.yoojia.inputs.StaticScheme;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.pojo.login.Org;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.utils.TimePickerDialog;
import com.sphd.emanu.utils.imageselect.PicassoImageLoader;
import com.wzutils.TimeUtils;
import com.yancy.gallerypick.config.GalleryConfig;
import com.yancy.gallerypick.config.GalleryPick;
import com.yancy.gallerypick.inter.IHandlerCallBack;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * @Author Hu
 * @Time 2017/7/27 -- 14:10.
 * @Email 87683202@qq.com
 */
public class OrgSettingActivity extends MVPBaseActivity<OrgSettingContract.View, OrgSettingPresenter> implements
        OrgSettingContract.View, TimePickerDialog.TimePickerDialogInterface, AMapLocationListener {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.toolbar_layout)
    CollapsingToolbarLayout toolbarLayout;
    @BindView(R.id.app_bar)
    AppBarLayout appBar;
    @BindView(R.id.fab)
    FloatingActionButton fab;
    @BindView(R.id.org_name)
    MaterialEditText orgName;
    @BindView(R.id.org_addr)
    MaterialEditText orgAddr;
    @BindView(R.id.org_phone)
    MaterialEditText orgPhone;
    @BindView(R.id.org_introduce)
    MaterialEditText orgIntroduce;
    Intent intent;
    User user;
    Bundle bundle;
    TimePickerDialog mTimePickerDialog;
    @BindView(R.id.bengin_time)
    TextView benginTime;
    @BindView(R.id.end_time)
    TextView endTime;
    int type = 0;
    @BindView(R.id.org_loc)
    ImageView orgLoc;
    @BindView(R.id.org_img)
    ImageView orgImg;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private GalleryConfig galleryConfig;
    private IHandlerCallBack iHandlerCallBack;
    private final int PERMISSIONS_REQUEST_READ_CONTACTS = 8;
    private List<String> path = new ArrayList<>();
    private double lon;
    private double lat;
    boolean isImg = false;
    private static final String TAG = "OrgSettingActivity";
    private Org org;
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };

    private static final int PERMISSON_REQUESTCODE = 0;

    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;
    AndroidNextInputs inputs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_org_setting);
        ButterKnife.bind(this);
        initView();

        initEvent();
    }


    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());

    }


    private void initView() {
        setTitleBar(toolbar, "店铺设置");
        inputs = new AndroidNextInputs();
        inputs.add(orgName, StaticScheme.NotBlank(), StaticScheme.Required())
                .add(orgAddr, StaticScheme.NotBlank(), StaticScheme.Required())
                .add(orgPhone, StaticScheme.ChineseMobile());
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        if (!user.getRoleid().equals("2")){
            fab.setVisibility(View.GONE);
        }
        mTimePickerDialog = new TimePickerDialog(this);
        initGallery();
        init();
        initLocation();
        addData();
    }

    /**
     * 跳转返回的数据
     */
    private void initGallery() {
        iHandlerCallBack = new IHandlerCallBack() {
            @Override
            public void onStart() {
                Log.i(TAG, "onStart: 开启");
            }

            @Override
            public void onSuccess(List<String> photoList) {
                Log.e(TAG, "onSuccess: 返回数据");
                path.clear();
                for (String s : photoList) {
                    Log.e(TAG + "->>>", s);
                    path.add(s);
                }
                if (path.size() != 0) {

                    setImage(orgImg, "file://" + path.get(0));
                }
            }

            @Override
            public void onCancel() {
                toast("取消");
                Log.e(TAG, "onCancel: 取消");
            }

            @Override
            public void onFinish() {
                Log.e(TAG, "onFinish: 结束");
            }

            @Override
            public void onError() {
                toast("出错了，请重试！");
                Log.e(TAG, "onError: 出错");
            }
        };

    }

    private void init() {
        galleryConfig = new GalleryConfig.Builder()
                .imageLoader(new PicassoImageLoader())    // ImageLoader 加载框架（必填）
                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.sphd.emanu.fileprovider")   // provider(必填)
                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(true)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(true, 1, 1, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build();
    }

    private void addData() {
        showProgressDialog();
        mPresenter.selectOrg(user.getOid());
    }

    /**
     * 初始化定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void initLocation() {
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(this);
    }

    /**
     * 默认的定位参数
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private AMapLocationClientOption getDefaultOption() {
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    @Override
    public void setBean(Org org) {
        this.org = org;
        dissProgressDialog();
        lon = Double.valueOf(org.getXwgs84().toString());
        lat = Double.valueOf(org.getYwgs84().toString());
        orgName.setText(org.getName());
        orgAddr.setText(org.getAddress());
        orgPhone.setText(org.getPhone());
        orgIntroduce.setText(org.getDescription());
        setImage(orgImg, Constant.HTTPTITLE_Base + org.getImg());
        benginTime.setText(TimeUtils.dateToString(org.getConfig().getOpeningTime(), TimeUtils.HOUR_MIN));
        endTime.setText(TimeUtils.dateToString(org.getConfig().getClosingTime(), TimeUtils.HOUR_MIN));

    }

    @OnClick({R.id.bengin_time, R.id.end_time, R.id.fab, R.id.org_loc, R.id.org_img})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.org_img:
                if (isNeedCheck) {
                    GalleryPick.getInstance().setGalleryConfig(galleryConfig).open((Activity) context);
                } else {
                    new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("缺少必要的定位权限，是否要开启权限？").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            isNeedCheck = true;
                            checkPermissions(needPermissions);
                        }
                    }).setConfirmText("不用了").show();
                }


                break;
            case R.id.bengin_time:
                type = 0;
                mTimePickerDialog.showTimePickerDialog();
                break;
            case R.id.end_time:
                type = 1;
                mTimePickerDialog.showTimePickerDialog();
                break;
            case R.id.org_loc:

                if (isNeedCheck) {
                    // 设置定位参数
                    locationClient.setLocationOption(locationOption);
                    // 启动定位
                    locationClient.startLocation();
                    startFlick(orgLoc);
                } else {
                    new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("缺少必要的定位权限，是否要开启权限？").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            isNeedCheck = true;
                            checkPermissions(needPermissions);
                        }
                    }).setConfirmText("不用了").show();
                }
                break;
            case R.id.fab:
                if (inputs.test()) {
                    showProgressDialog();
                    if (path.size() != 0) {
                        mPresenter.updateOrg(org.getId(), getText(orgName), getText(orgAddr), getText(orgPhone), (Constant.YEAR + benginTime.getText().toString() + ":00")
                                , (Constant.YEAR + endTime.getText().toString() + ":00"), lon, lat, getText(orgIntroduce),
                                prepareFilePart("image", path.get(0)));
                    } else {
                        mPresenter.updateOrg(org.getId(), getText(orgName), getText(orgAddr), getText(orgPhone), (Constant.YEAR + benginTime.getText().toString() + ":00")
                                , (Constant.YEAR + endTime.getText().toString() + ":00"), lon, lat, getText(orgIntroduce));

                    }
                } else {
                    toast("请按要求填写");
                }

                break;
        }

    }

    private String getText(MaterialEditText materialEditText) {
        if (null == materialEditText) {
            return "";
        }
        return materialEditText.getText().toString().trim();
    }

    /**
     * 开启View闪烁效果
     */
    private void startFlick(View view) {
        if (null == view) {
            return;
        }
        Animation alphaAnimation = new AlphaAnimation(1, 0.1f);
        alphaAnimation.setDuration(300);
        alphaAnimation.setInterpolator(new LinearInterpolator());
        alphaAnimation.setRepeatCount(Animation.INFINITE);
        alphaAnimation.setRepeatMode(Animation.REVERSE);
        view.startAnimation(alphaAnimation);
    }

    /**
     * 取消View闪烁效果
     */
    private void stopFlick(View view) {
        if (null == view) {
            return;
        }
        view.clearAnimation();
    }

    //时间选择器----------确定
    @Override
    public void positiveListener() {
        String hour = mTimePickerDialog.getHour() < 10 ? ("0" + mTimePickerDialog.getHour()) : String.valueOf(mTimePickerDialog.getHour());
        String minute = mTimePickerDialog.getMinute() < 10 ? ("0" + mTimePickerDialog.getMinute()) : String.valueOf(mTimePickerDialog.getMinute());
        if (type == 0) {
            benginTime.setText(hour + ":" + minute);
        } else {
            endTime.setText(hour + ":" + minute);
        }
    }

    @Override
    public void negativeListener() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedCheck) {
            checkPermissions(needPermissions);
        }
    }

    @Override
    public void setRes(int res) {
        dissProgressDialog();
        if (res == 1) {
            toast(getString(R.string.up_success));
        } else {
            toast(getString(R.string.up_failure));
        }
    }

    /**
     * @param
     * @since 2.5.0
     */
    private void checkPermissions(String... permissions) {
        List<String> needRequestPermissonList = findDeniedPermissions(permissions);
        if (null != needRequestPermissonList
                && needRequestPermissonList.size() > 0) {
            ActivityCompat.requestPermissions(this,
                    needRequestPermissonList.toArray(
                            new String[needRequestPermissonList.size()]),
                    PERMISSON_REQUESTCODE);
        }
    }

    /**
     * 获取权限集中需要申请权限的列表
     *
     * @param permissions
     * @return
     * @since 2.5.0
     */
    private List<String> findDeniedPermissions(String[] permissions) {
        List<String> needRequestPermissonList = new ArrayList<String>();
        for (String perm : permissions) {
            if (ContextCompat.checkSelfPermission(this,
                    perm) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                    this, perm)) {
                needRequestPermissonList.add(perm);
            }
        }
        return needRequestPermissonList;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] paramArrayOfInt) {
        super.onRequestPermissionsResult(requestCode, permissions, paramArrayOfInt);
        if (requestCode == PERMISSON_REQUESTCODE) {
            if (!verifyPermissions(paramArrayOfInt)) {
                showMissingPermissionDialog();
                isNeedCheck = false;
            }
        }
    }

    /**
     * 显示提示信息
     *
     * @since 2.5.0
     */
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.notifyTitle);
        builder.setMessage(R.string.notifyMsg);

        // 拒绝, 退出应用
        builder.setNegativeButton(R.string.cancel,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        toast("缺少必要的权限，请手动填写店铺地址。");
                    }
                });

        builder.setPositiveButton(R.string.setting,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startAppSettings();
                    }
                });

        builder.setCancelable(false);

        builder.show();
    }

    /**
     * 检测是否说有的权限都已经授权
     *
     * @param grantResults
     * @return
     * @since 2.5.0
     */
    private boolean verifyPermissions(int[] grantResults) {
        for (int result : grantResults) {
            if (result != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 启动应用的设置
     *
     * @since 2.5.0
     */
    private void startAppSettings() {
        Intent intent = new Intent(
                Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    public void onLocationChanged(AMapLocation location) {
        if (null != location) {
            StringBuffer sb = new StringBuffer();
            //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
            if (location.getErrorCode() == 0) {
                stopLocation();
                toast("定位成功,精度" + location.getAccuracy() + "米");
                stopFlick(orgLoc);
                lon = location.getLongitude();
                lat = location.getLatitude();
                orgAddr.setText(location.getAddress());
            } else {
                //定位失败
                toast("定位失败，请手动填写店铺地址");
                orgAddr.setText(null);
            }
        } else {
            toast("定位失败，请手动填写店铺地址");
            orgAddr.setText(null);
        }
    }

    /**
     * 停止定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void stopLocation() {
        // 停止定位
        locationClient.stopLocation();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroyLocation();
    }

    /**
     * 销毁定位
     *
     * @author hongming.wang
     * @since 2.8.0
     */
    private void destroyLocation() {
        if (null != locationClient) {
            /**
             * 如果AMapLocationClient是在当前Activity实例化的，
             * 在Activity的onDestroy中一定要执行AMapLocationClient的onDestroy
             */
            locationClient.onDestroy();
            locationClient = null;
            locationOption = null;
        }
    }
}
